
package com.college.action.user;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.college.constant.ConfigConstant;
import com.college.constant.SystemConstant;
import com.college.constant.UserConstant.RoleType;
import com.college.entity.Classes;
import com.college.entity.User;
import com.college.entity.vo.JsonVo;
import com.college.form.UserForm;
import com.college.service.SystemUserService;
import com.college.service.UserService;
import com.college.util.AuthUtils;
import com.college.util.HttpUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;

/**
 * @author bob
 * 
 */

@Controller
@RequestMapping("/auth")
public class AuthAction extends BaseAction {

	/**
	 * Kaptcha 验证码
	 */
	@Autowired
	private DefaultKaptcha captchaProducer;
	
	@Autowired
	private UserService userService;
	
	
	@Autowired
	private SystemUserService systemUserService;


	@RequestMapping(value = "login.htm", method = RequestMethod.GET)
	public String userLogin(HttpServletRequest request, ModelMap modelMap) {
		return "user/pages/login";
	}
	
	@RequestMapping(value = "register.htm", method = RequestMethod.GET)
	public String userRegister(HttpServletRequest request, ModelMap modelMap) {
		return "user/pages/register";
	}

	@RequestMapping(value = "logout.htm", method = RequestMethod.GET)
	public String userLogout(HttpServletRequest request, ModelMap modelMap) {
		request.getSession().removeAttribute(SystemConstant.SESSION_ADMIN);
		return "redirect:" + HttpUtils.getBasePath(request);
	}
	
	
	/**
	 * 注册成功后，重定向到对应的页面
	 * 
	 */
	@RequestMapping(value = "registerSuccess.htm", method = RequestMethod.GET)
	public String userRegisterSuccess(HttpServletRequest request, ModelMap modelMap) {
		return "user/pages/regSuccess";
	}
	
	
	
	/**
	 * 
	 * @param email
	 * @param password
	 * @param captcha
	 * @param request
	 * @param modelMap
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "login.json", method = RequestMethod.POST)
	public JsonVo<String> userLogin(
			HttpServletRequest request, ModelMap modelMap,
			@RequestParam(value = "email") String email,
			@RequestParam(value = "password") String password,
			@RequestParam(value = "roleType") RoleType roleType
			) {
		JsonVo<String> json = new JsonVo<String>();

		try {
			
			User user  = new User();
			user.setEmail(email);
			user.setPassword(password);
			user.setRoleType(roleType);
			/*String kaptcha = (String) request.getSession().getAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);*/
			if (!EmailValidator.getInstance().isValid(user.getEmail())) {
				json.getErrors().put("email", "邮件格式错误");
			}
			if (StringUtils.isBlank(user.getPassword())) {
				json.getErrors().put("password", "密码不能为空");
			} else if (user.getPassword().length() < 3 && user.getPassword().length() > 30) {
				json.getErrors().put("password", "密码最少3个字符，最多30个字符");
			}
			if(StringUtils.isBlank(user.getRoleType().toString())){
				json.getErrors().put("roleType", "登录角色错误");
			}
			/*// 校验验证码
			if (StringUtils.isNotBlank(kaptcha)
					&& kaptcha.equalsIgnoreCase(captcha)) {

			} else {
				json.getErrors().put("captcha", "验证码错误");
			}*/
			this.validate(json);

			User existUser = userService.findUserByEmail(user.getEmail());
			if(existUser == null){
				json.getErrors().put("email", "邮箱错误");
			}else if(!AuthUtils.getPassword(user.getPassword(), user.getEmail()).equals(existUser.getPassword())){
				json.getErrors().put("password", "密码错误");
			}else if(!existUser.getRoleType().equals(user.getRoleType())){
				json.getErrors().put("roleType", "角色错误");
			}
			if(json.getErrors().size() > 0){
				json.setResult(false);
			}else{
				List<Classes> classesList = systemUserService.getMyClassesList(existUser.getUserId());
				List<String> classIdList = null;
				if(classesList != null && classesList.size() > 0){
					classIdList = new ArrayList<String>();
					for(int i = 0,l = classesList.size(); i < l; i++){
						classIdList.add(i, classesList.get(i).getClassId());
					}
				}
				existUser.setClassIdList(classIdList);
				request.getSession().setAttribute(SystemConstant.SESSION_USER, existUser);
			}
			
			//adminService.adminLogin(email, password, request);

		} catch (Exception e) {
			// 异常，重置验证码
			request.getSession().removeAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			json.setResult(false);
			json.getErrors().put("password", "邮箱或密码错误");
			//json.setMsg("change_captcha");
		}
		return json;
	}
	
	
	@RequestMapping(value = "register.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> userRegister(
			HttpServletRequest request, ModelMap modelMap, UserForm userForm,User user) {
		JsonVo<String> json = new JsonVo<String>();

		try {
			String kaptcha = (String) request.getSession().getAttribute(ConfigConstant.SYS_CAPTCHA);
			if (!EmailValidator.getInstance().isValid(userForm.getEmail())) {
				json.getErrors().put("email", "邮件格式错误");
			}
			if (StringUtils.isBlank(userForm.getPassword())) {
				json.getErrors().put("password", "密码不能为空");
			} else if (userForm.getPassword().length() < 4 && userForm.getPassword().length() > 30) {
				json.getErrors().put("password", "密码最少4个字符，最多30个字符");
			}
			// 校验验证码
			if (StringUtils.isNotBlank(kaptcha)
					&& kaptcha.equalsIgnoreCase(userForm.getCaptcha())) {

			} else {
				json.getErrors().put("captcha", "验证码错误");
			}
			this.validate(json);

			user.setUserId(UUID.randomUUID().toString());
			user.setPassword(AuthUtils.getPassword(userForm.getPassword(), userForm.getEmail()));
			user.setRealName(userForm.getRealName());
			user.setRoleType(userForm.getRoleType());
			user.setEmail(userForm.getEmail());
			userService.userRegister(user);
			
			request.getSession().setAttribute(SystemConstant.SESSION_USER, user);//保存user信息到session中

		} catch (Exception e) {
			// 异常，重置验证码
			request.getSession().removeAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			json.setResult(false);
			json.getErrors().put("password", "邮箱或密码错误");
			json.setMsg("change_captcha");
		}
		return json;
	}

	/**
	 * 生成验证码
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "captcha.htm", method = RequestMethod.GET)
	public void captcha(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		request.getSession().setAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
	
	
	@RequestMapping(value = "validateAuth.htm", method = RequestMethod.GET)
	 public void checkUserEmailOrValidateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

			String checkType = request.getParameter("checkType");
			
	    	String inputValue = request.getParameter("inputValue");//邮箱或者验证码的值
	    	JSONObject json = new JSONObject();
	    	Boolean available = false;
			if(StringUtils.isNotBlank(inputValue) && "emailType".equals(checkType)){
				User user = userService.findUserByEmail(inputValue);
				//int result = 1;
				 available = user != null  ? false : true;
			}
			
			if(StringUtils.isNotBlank(inputValue) && "validatorCode".equals(checkType)){
				Object sessionCode = request.getSession().getAttribute(ConfigConstant.SYS_CAPTCHA);
				available = inputValue.equals(sessionCode.toString()) ? true : false;
			}
			json.put("valid",available);
			PrintWriter out = response.getWriter();
			out.print(json);

	    }
}
